import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../constants/colors.dart';
import '../widgets/gradient_background.dart';
import '../widgets/app_card.dart';
import '../models/hexagram.dart';
import '../services/hexagram_service.dart';
import 'hexagram_detail_page.dart';

class HexagramTextsPage extends StatefulWidget {
  const HexagramTextsPage({Key? key}) : super(key: key);

  @override
  State<HexagramTextsPage> createState() => _HexagramTextsPageState();
}

class _HexagramTextsPageState extends State<HexagramTextsPage> {
  final HexagramService _hexagramService = HexagramService();
  late List<Hexagram> _hexagrams;
  List<Hexagram> _filteredHexagrams = [];
  
  // 五行对应的颜色
  final Map<String, List<Color>> _elementColors = {
    '金': [Color(0xFFFFD700), Color(0xFFDAA520)],
    '木': [Color(0xFF4CAF50), Color(0xFF2E7D32)],
    '水': [Color(0xFF2196F3), Color(0xFF0D47A1)],
    '火': [Color(0xFFFF5722), Color(0xFFD84315)],
    '土': [Color(0xFF795548), Color(0xFF4E342E)],
  };
  
  @override
  void initState() {
    super.initState();
    _hexagrams = _hexagramService.getAllHexagrams();
    _filteredHexagrams = _hexagrams;
  }
  
  void _filterHexagrams(String query) {
    setState(() {
      if (query.isEmpty) {
        _filteredHexagrams = _hexagrams;
      } else {
        _filteredHexagrams = _hexagrams
            .where((hexagram) => 
                hexagram.name.contains(query) || 
                hexagram.description.contains(query))
            .toList();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GradientBackground(
      child: SafeArea(
        child: Column(
          children: [
            // 顶部栏
            Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: 20,
                vertical: 15,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(width: 24),
                  Expanded(
                    child: Center(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          SvgPicture.asset(
                            'assets/icons/app_logo.svg',
                            width: 28,
                            height: 28,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            '合象大全',
                            style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              color: Colors.black,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(width: 24),
                ],
              ),
            ),
            
            // 搜索框
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.9),
                  borderRadius: BorderRadius.circular(30),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 10,
                      offset: const Offset(0, 3),
                    ),
                  ],
                ),
                child: TextField(
                  onChanged: _filterHexagrams,
                  decoration: InputDecoration(
                    hintText: '搜索合象名称或解析',
                    prefixIcon: const Icon(Icons.search, color: AppColors.primaryGradientStart),
                    border: InputBorder.none,
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 20,
                      vertical: 15,
                    ),
                  ),
                ),
              ),
            ),
            
            // 卦象列表
            Expanded(
              child: _filteredHexagrams.isEmpty
                  ? Center(
                      child: Text(
                        '没有找到匹配的卦象',
                        style: TextStyle(
                          color: Colors.black.withOpacity(0.7),
                          fontSize: 16,
                        ),
                      ),
                    )
                  : _buildGridView(_filteredHexagrams),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildGridView(List<Hexagram> hexagrams) {
    return GridView.builder(
      padding: const EdgeInsets.all(16),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 0.8, // 进一步调整宽高比，给卡片更多的高度
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
      ),
      itemCount: hexagrams.length,
      itemBuilder: (context, index) {
        final hexagram = hexagrams[index];
        return _buildHexagramGridCard(context, hexagram);
      },
    );
  }
  
  Widget _buildHexagramGridCard(BuildContext context, Hexagram hexagram) {
    // 获取上下卦对应的颜色
    List<Color> upperColors = _elementColors[hexagram.upperElement] ?? 
        [AppColors.primaryGradientStart, AppColors.primaryGradientEnd];
    List<Color> lowerColors = _elementColors[hexagram.lowerElement] ?? 
        [AppColors.primaryGradientStart, AppColors.primaryGradientEnd];
    
    return AppCard(
      onTap: () {
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => HexagramDetailPage(
              hexagram: hexagram,
            ),
          ),
        );
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 卦象符号
          Container(
            width: 70,
            height: 70,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [upperColors[0], lowerColors[0]],
              ),
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: upperColors[0].withOpacity(0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 3),
                ),
              ],
            ),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    hexagram.upperSymbol,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    hexagram.lowerSymbol,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 10),
          // 卦名
          Text(
            hexagram.name,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: AppColors.textPrimary,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 4),
          // 五行关系
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
            decoration: BoxDecoration(
              color: Colors.grey.withOpacity(0.1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Text(
              '${hexagram.upperElement}${hexagram.lowerElement} · ${hexagram.elementRelation}',
              style: TextStyle(
                fontSize: 12,
                color: AppColors.textSecondary.withOpacity(0.8),
              ),
            ),
          ),
        ],
      ),
    );
  }
}